package ruc.grs.ypytd.dao.db;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.log4j.Logger;

public class DataBase {
	final static Logger log = Logger.getLogger(DataBase.class);
	Connection conn = null;

	public DataBase() {
		try {
			conn = OracleDataSource.getConnection();
		} catch (SQLException e) {
			log.error("无法获得数据库连接", e);
		}
	}

	public Connection getExistedConnection() {
		return conn;
	}

	/**
	 * 指定数据库连接做查询
	 * 
	 * @param conn
	 * @param sql
	 * @return
	 */
	public synchronized ResultSet executeQuery(Connection conn, String sql) {
		ResultSet res = null;
		try {
			Statement stmt = conn
					.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
							ResultSet.CONCUR_UPDATABLE);
			res = stmt.executeQuery(sql);

		} catch (SQLException e) {
			e.printStackTrace();
		}
		return res;
	}

	public synchronized ResultSet executeQuery(String sql) {
		ResultSet res = null;
		try {
			res = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
					ResultSet.CONCUR_UPDATABLE).executeQuery(sql);

		} catch (SQLException e) {
			log.error(e.getMessage(), e);
		}
		return res;
	}

	/**
	 * 执行SQL查询，返回ResultSet,此结果集不能循环
	 * 
	 * @param sql
	 * @return
	 */
	public synchronized ResultSet query(String sql) {
		ResultSet res = null;
		try {
			res = conn.createStatement().executeQuery(sql);
		} catch (SQLException e) {
			log.error(e.getMessage(), e);
		}
		return res;
	}

	/**
	 * 执行更新操作
	 * 
	 * @param sql
	 */
	public synchronized int executeUpdate(String sql) {
		int result = 0;
		try {
			result = conn.createStatement().executeUpdate(sql);
		} catch (SQLException e) {
			log.error(e.getMessage(), e);
		}
		return result;
	}

	/**
	 * 关闭数据库连接，返回到连接池
	 */
	public void close() {
		try {
			if (conn != null) {
				conn.close();
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		} finally {
			conn = null;
		}
	}

}
